import { driver, DriveStep } from "driver.js";
import "driver.js/dist/driver.css";

export default defineContentScript({
  matches: ["<all_urls>"],
  main() {
    // 创建统一的 driver.js 实例
    let driverInstance: any = null;

    // 获取或创建driver实例
    function getDriverInstance(config?: any) {
      // 如果已有实例且没有新配置，直接返回
      if (driverInstance && !config) {
        return driverInstance;
      }

      // 销毁旧实例
      if (driverInstance) {
        try {
          driverInstance.destroy();
        } catch (e) {
          console.warn("销毁旧driver实例时出错:", e);
        }
      }

      // 创建新实例
      const defaultConfig = {
        overlayOpacity: 0.3,
        onPopoverRender: (popover: any, { config, state }: any) => {
          const wrapper = popover.wrapper;
          wrapper.removeChild(popover.closeButton);
          wrapper.removeChild(popover.footer);

          // 应用自定义样式
          applyCustomStyles(config.customStyles);
        },
        steps: [
          {
            element: "body",
            popover: {
              title: "欢迎使用页面引导",
              description:
                "这是一个基于 driver.js 的页面引导插件，将为您介绍页面的主要功能。",
              side: "left",
              align: "start",
            },
          },
        ],
      };

      driverInstance = driver(Object.assign({}, defaultConfig, config));
      return driverInstance;
    }

    // 应用自定义样式
    function applyCustomStyles(customStyles?: string) {
      // 移除之前的自定义样式
      const existingStyle = document.getElementById("driver-custom-styles");
      if (existingStyle) {
        existingStyle.remove();
      }

      // 如果有自定义样式，添加到页面
      if (customStyles) {
        const styleElement = document.createElement("style");
        styleElement.id = "driver-custom-styles";
        styleElement.textContent = customStyles;
        document.head.appendChild(styleElement);
      }
    }

    // 监听来自 popup 的消息
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      if (request.action === "startTour") {
        startPageTour(request.customStyles);
        sendResponse({ success: true });
      } else if (request.action === "stopTour") {
        const driver = getDriverInstance();
        driver.destroy();
        driverInstance = null; // 重置实例
        // 清理自定义样式
        applyCustomStyles();
        sendResponse({ success: true });
      } else if (request.action === "startCustomTour") {
        startCustomTour(request.data, request.customStyles);
        sendResponse({ success: true });
      } else if (request.action === "getSelectedElement") {
        const selector = getSelectedElementSelector();
        sendResponse({ selector });
      } else if (request.action === "startElementPicker") {
        startElementPicker(sendResponse);
        return true; // 保持消息通道开放
      }
    });

    // 获取开发者工具中选中的元素选择器
    function getSelectedElementSelector(): string | null {
      try {
        // 方法1: 尝试通过console API获取$0
        let selectedElement = null;

        // 尝试多种方式获取选中的元素
        try {
          // 直接访问$0
          selectedElement = (window as any).$0;
        } catch (e) {
          // 如果直接访问失败，尝试通过console
          try {
            selectedElement = (console as any).$0;
          } catch (e2) {
            // 尝试通过全局对象
            try {
              selectedElement = (globalThis as any).$0;
            } catch (e3) {
              console.warn("无法通过常规方式获取$0");
            }
          }
        }

        if (selectedElement && selectedElement.nodeType === Node.ELEMENT_NODE) {
          console.log("成功获取到选中的元素:", selectedElement);
          return generateSelector(selectedElement);
        }

        // 方法2: 如果$0不可用，尝试获取最近点击的元素
        const lastClickedElement = getLastClickedElement();
        if (lastClickedElement) {
          console.log("使用最近点击的元素:", lastClickedElement);
          return generateSelector(lastClickedElement);
        }
      } catch (error) {
        console.warn("获取选中元素时出错:", error);
      }
      return null;
    }

    // 跟踪最近点击的元素
    let lastClickedElement: Element | null = null;

    // 监听页面点击事件来记录最近点击的元素
    document.addEventListener(
      "click",
      (event) => {
        if (
          event.target &&
          (event.target as Element).nodeType === Node.ELEMENT_NODE
        ) {
          lastClickedElement = event.target as Element;
          console.log("记录点击的元素:", lastClickedElement);
        }
      },
      true
    );

    // 获取最近点击的元素
    function getLastClickedElement(): Element | null {
      return lastClickedElement;
    }

    // 元素选择器状态
    let isPickingElement = false;
    let pickerCallback: ((response: any) => void) | null = null;

    // 启动元素选择器
    function startElementPicker(callback: (response: any) => void) {
      isPickingElement = true;
      pickerCallback = callback;

      // 添加选择器样式
      addPickerStyles();

      // 显示提示信息
      showPickerToast("请点击页面中的任意元素来选择它，按ESC键取消");

      // 添加事件监听器
      document.addEventListener("mouseover", highlightElement, true);
      document.addEventListener("mouseout", removeHighlight, true);
      document.addEventListener("click", selectElement, true);
      document.addEventListener("keydown", handlePickerKeydown, true);
    }

    // 停止元素选择器
    function stopElementPicker(selectedElement?: Element) {
      isPickingElement = false;

      // 移除事件监听器
      document.removeEventListener("mouseover", highlightElement, true);
      document.removeEventListener("mouseout", removeHighlight, true);
      document.removeEventListener("click", selectElement, true);
      document.removeEventListener("keydown", handlePickerKeydown, true);

      // 移除高亮
      removeHighlight();

      // 移除提示信息
      removePickerToast();

      // 移除样式
      removePickerStyles();

      // 处理选择结果
      if (selectedElement) {
        const selector = generateSelector(selectedElement);

        // 验证生成的选择器是否能正确找到元素
        try {
          const testElement = document.querySelector(selector);
          if (testElement === selectedElement) {
            console.log("✅ 选择器验证成功:", selector);
            showPickerToast(
              `选择器生成成功: ${selector}\n请重新打开插件查看结果`
            );

            // 保存选择结果到storage
            chrome.storage.local.set({
              selectedElementSelector: selector,
            });

            setTimeout(() => removePickerToast(), 3000);
          } else {
            console.warn("⚠️ 选择器可能不唯一:", selector);
            showPickerToast(
              `警告: 选择器可能不唯一: ${selector}\n请重新打开插件查看结果`
            );

            // 即使有警告也保存结果
            chrome.storage.local.set({
              selectedElementSelector: selector,
            });

            setTimeout(() => removePickerToast(), 4000);
          }
        } catch (error) {
          console.error("❌ 选择器语法错误:", selector, error);
          showPickerToast(`错误: 选择器语法有误: ${selector}`);
          setTimeout(() => removePickerToast(), 3000);
        }
      } else {
        // 用户取消了选择
        showPickerToast("已取消元素选择");

        // 清理选择状态
        chrome.storage.local.remove([
          "pickingInProgress",
          "pickingElementForStep",
        ]);

        setTimeout(() => removePickerToast(), 2000);
      }

      // 发送响应（如果有回调）
      if (pickerCallback) {
        pickerCallback({ success: true });
        pickerCallback = null;
      }
    }

    // 跟踪最后高亮的元素
    let lastHighlightedElement: Element | null = null;

    // 鼠标悬停时高亮元素
    function highlightElement(event: MouseEvent) {
      if (!isPickingElement) return;

      const element = getActualTargetElement(event);
      if (element && element !== lastHighlightedElement) {
        removeHighlight();

        if (
          element.nodeType === Node.ELEMENT_NODE &&
          !shouldSkipElement(element)
        ) {
          element.classList.add("__element-picker-highlight");
          lastHighlightedElement = element;

          showElementInfo(element, event);
        }
      }
    }

    // 显示元素信息
    function showElementInfo(element: Element, event: MouseEvent) {
      const tagName = element.tagName.toLowerCase();
      const className = element.className
        ? `.${element.className.split(" ").join(".")}`
        : "";
      const id = element.id ? `#${element.id}` : "";
      const text = element.textContent?.trim().substring(0, 30) || "";

      const info = `${tagName}${id}${className}${text ? ` "${text}..."` : ""}`;

      // 移除之前的信息提示
      const existingInfo = document.querySelector(".__element-picker-info");
      if (existingInfo) {
        existingInfo.remove();
      }

      // 创建新的信息提示
      const infoDiv = document.createElement("div");
      infoDiv.className = "__element-picker-info";
      infoDiv.textContent = info;
      infoDiv.style.cssText = `
         position: fixed;
         top: ${event.clientY + 10}px;
         left: ${event.clientX + 10}px;
         background: rgba(0, 0, 0, 0.8);
         color: white;
         padding: 4px 8px;
         border-radius: 4px;
         font-size: 12px;
         font-family: monospace;
         z-index: 999999;
         pointer-events: none;
         max-width: 300px;
         word-break: break-all;
       `;

      document.body.appendChild(infoDiv);

      // 2秒后自动移除
      setTimeout(() => {
        if (infoDiv.parentNode) {
          infoDiv.remove();
        }
      }, 2000);
    }

    // 移除高亮
    function removeHighlight() {
      const highlighted = document.querySelectorAll(
        ".__element-picker-highlight"
      );
      highlighted.forEach((el) =>
        el.classList.remove("__element-picker-highlight")
      );

      // 移除元素信息提示
      const infoElements = document.querySelectorAll(".__element-picker-info");
      infoElements.forEach((el) => el.remove());

      lastHighlightedElement = null;
    }

    // 选择元素
    function selectElement(event: MouseEvent) {
      if (!isPickingElement) return;

      event.preventDefault();
      event.stopPropagation();

      const element = getActualTargetElement(event);
      if (element && element.nodeType === Node.ELEMENT_NODE) {
        console.log(
          "🎯 选中元素:",
          element,
          "标签:",
          element.tagName,
          "类名:",
          element.className
        );
        stopElementPicker(element);
      } else {
        console.warn("⚠️ 无法选中元素，event.target:", event.target);
        showPickerToast("无法选中该元素，请尝试点击其他位置");
        setTimeout(() => removePickerToast(), 2000);
      }
    }

    // 获取实际的目标元素 - 简化直接的方法
    function getActualTargetElement(event: MouseEvent): Element | null {
      let target = event.target as Element;

      // 如果点击的是文本节点，获取其父元素
      if (target && target.nodeType === Node.TEXT_NODE) {
        target = target.parentElement as Element;
      }

      console.log(
        "直接选择目标元素:",
        target,
        "标签:",
        target?.tagName,
        "类名:",
        target?.className
      );

      return target;
    }

    // 判断是否应该跳过某些元素
    function shouldSkipElement(element: Element): boolean {
      if (!element) return true;

      const tagName = element.tagName.toLowerCase();
      const className = element.className || "";

      // 跳过我们自己添加的元素
      if (className.includes("__element-picker")) {
        return true;
      }

      // 跳过不应该选择的标签
      const skipTags = [
        "html",
        "head",
        "meta",
        "title",
        "script",
        "style",
        "link",
      ];
      if (skipTags.includes(tagName)) {
        return true;
      }

      // 跳过不可见的元素
      const style = window.getComputedStyle(element);
      if (style.display === "none" || style.visibility === "hidden") {
        return true;
      }

      return false;
    }

    // 处理键盘事件
    function handlePickerKeydown(event: KeyboardEvent) {
      if (!isPickingElement) return;

      if (event.key === "Escape") {
        event.preventDefault();
        stopElementPicker();
      }
    }

    // 添加选择器样式
    function addPickerStyles() {
      if (document.getElementById("__element-picker-styles")) return;

      const style = document.createElement("style");
      style.id = "__element-picker-styles";
      style.textContent = `
         .__element-picker-highlight {
           outline: 3px solid #007bff !important;
           outline-offset: 2px !important;
           background-color: rgba(0, 123, 255, 0.15) !important;
           cursor: crosshair !important;
           box-shadow: 0 0 10px rgba(0, 123, 255, 0.3) !important;
           position: relative !important;
           z-index: 999998 !important;
         }
         .__element-picker-toast {
           position: fixed !important;
           top: 20px !important;
           left: 50% !important;
           transform: translateX(-50%) !important;
           background: #333 !important;
           color: white !important;
           padding: 12px 20px !important;
           border-radius: 6px !important;
           font-size: 14px !important;
           font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
           z-index: 999999 !important;
           box-shadow: 0 4px 12px rgba(0,0,0,0.3) !important;
           pointer-events: none !important;
           white-space: pre-line !important;
           max-width: 500px !important;
           text-align: center !important;
         }
         .__element-picker-highlight-multiple {
           outline: 2px dashed #ff6b35 !important;
           outline-offset: 1px !important;
           background-color: rgba(255, 107, 53, 0.08) !important;
           cursor: crosshair !important;
           position: relative !important;
           z-index: 999997 !important;
         }
         .__element-picker-info {
           position: fixed !important;
           background: rgba(0, 0, 0, 0.8) !important;
           color: white !important;
           padding: 4px 8px !important;
           border-radius: 4px !important;
           font-size: 12px !important;
           font-family: monospace !important;
           z-index: 999999 !important;
           pointer-events: none !important;
           max-width: 300px !important;
           word-break: break-all !important;
         }
       `;
      document.head.appendChild(style);
    }

    // 移除选择器样式
    function removePickerStyles() {
      const style = document.getElementById("__element-picker-styles");
      if (style) {
        style.remove();
      }
    }

    // 显示提示信息
    function showPickerToast(message: string) {
      removePickerToast();

      const toast = document.createElement("div");
      toast.id = "__element-picker-toast";
      toast.className = "__element-picker-toast";
      toast.textContent = message;
      document.body.appendChild(toast);
    }

    // 移除提示信息
    function removePickerToast() {
      const toast = document.getElementById("__element-picker-toast");
      if (toast) {
        toast.remove();
      }
    }

    // 生成元素的CSS选择器
    function generateSelector(element: Element): string {
      console.log("🎯 开始生成选择器，目标元素:", element);

      // 1. 尝试使用ID（最高优先级）
      if (element.id) {
        const selector = `#${element.id}`;
        if (isUniqueSelector(selector, element)) {
          console.log("✅ 使用ID选择器:", selector);
          return selector;
        }
      }

      // 2. 尝试使用data-*属性（高优先级）
      const dataAttributes = [
        "data-testid",
        "data-id",
        "data-test",
        "data-cy",
        "data-automation-id",
      ];
      for (const attr of dataAttributes) {
        const value = element.getAttribute(attr);
        if (value) {
          const selector = `[${attr}="${value}"]`;
          if (isUniqueSelector(selector, element)) {
            console.log("✅ 使用data属性选择器:", selector);
            return selector;
          }
        }
      }

      // 3. 尝试使用稳定的类名组合
      const classList = Array.from(element.classList).filter((cls) => {
        // 过滤掉动态类名和临时类名
        return (
          !cls.includes("__element-picker") &&
          !cls.match(
            /^(hover|active|focus|selected|current|temp|tmp|loading|disabled)/
          ) &&
          !cls.match(/\d{6,}/) && // 过滤包含长数字的类名（可能是hash）
          !cls.match(/^[a-f0-9]{8,}$/i) && // 过滤纯hash类名
          cls.length > 1
        ); // 过滤单字符类名
      });

      if (classList.length > 0) {
        // 尝试单个类名
        for (const cls of classList) {
          const selector = `.${cls}`;
          if (isUniqueSelector(selector, element)) {
            console.log("✅ 使用单个类名选择器:", selector);
            return selector;
          }
        }

        // 尝试组合多个类名
        if (classList.length > 1) {
          const combinedSelector = `.${classList
            .slice(0, Math.min(3, classList.length))
            .join(".")}`;
          if (isUniqueSelector(combinedSelector, element)) {
            console.log("✅ 使用组合类名选择器:", combinedSelector);
            return combinedSelector;
          }
        }
      }

      // 4. 尝试使用其他属性
      const otherAttributes = [
        "name",
        "aria-label",
        "role",
        "type",
        "placeholder",
        "title",
      ];
      for (const attr of otherAttributes) {
        const value = element.getAttribute(attr);
        if (value) {
          const selector = `[${attr}="${value}"]`;
          if (isUniqueSelector(selector, element)) {
            console.log("✅ 使用属性选择器:", selector);
            return selector;
          }
        }
      }

      // 5. 尝试使用标签名 + 属性组合
      const tagName = element.tagName.toLowerCase();

      // 尝试标签名 + 类名组合
      if (classList.length > 0) {
        const tagClassSelector = `${tagName}.${classList[0]}`;
        if (isUniqueSelector(tagClassSelector, element)) {
          console.log("✅ 使用标签+类名选择器:", tagClassSelector);
          return tagClassSelector;
        }
      }

      // 6. 尝试使用文本内容结合其他属性（谨慎使用）
      const textContent = element.textContent?.trim();
      if (textContent && textContent.length > 2 && textContent.length < 30) {
        // 尝试结合标签名和文本长度特征
        const textLengthSelector = `${tagName}:nth-of-type(1)`;
        if (isUniqueSelector(textLengthSelector, element)) {
          console.log("✅ 使用标签位置选择器:", textLengthSelector);
          return textLengthSelector;
        }

        // 如果是按钮或链接，尝试使用部分文本匹配的属性选择器
        if (["button", "a", "span"].includes(tagName)) {
          // 检查是否有包含文本的title或aria-label属性
          const title = element.getAttribute("title");
          const ariaLabel = element.getAttribute("aria-label");

          if (title && title.includes(textContent.substring(0, 10))) {
            const titleSelector = `${tagName}[title*="${title.substring(
              0,
              15
            )}"]`;
            if (isUniqueSelector(titleSelector, element)) {
              console.log("✅ 使用title属性选择器:", titleSelector);
              return titleSelector;
            }
          }

          if (ariaLabel && ariaLabel.includes(textContent.substring(0, 10))) {
            const ariaSelector = `${tagName}[aria-label*="${ariaLabel.substring(
              0,
              15
            )}"]`;
            if (isUniqueSelector(ariaSelector, element)) {
              console.log("✅ 使用aria-label属性选择器:", ariaSelector);
              return ariaSelector;
            }
          }
        }
      }

      // 7. 生成基于位置的精确路径选择器（最后的回退方案）
      const pathSelector = getElementPath(element);
      console.log("⚠️ 使用路径选择器（可能不稳定）:", pathSelector);
      return pathSelector;
    }

    // 检查选择器是否唯一
    function isUniqueSelector(
      selector: string,
      targetElement: Element
    ): boolean {
      try {
        const elements = document.querySelectorAll(selector);
        return elements.length === 1 && elements[0] === targetElement;
      } catch (error) {
        console.warn("选择器语法错误:", selector, error);
        return false;
      }
    }

    // 生成元素的完整路径选择器
    function getElementPath(element: Element): string {
      const path: string[] = [];
      let current = element;

      while (
        current &&
        current.nodeType === Node.ELEMENT_NODE &&
        current !== document.body
      ) {
        let selector = current.tagName.toLowerCase();

        // 如果有ID，直接使用ID并停止
        if (current.id) {
          selector = `#${current.id}`;
          path.unshift(selector);
          break;
        }

        // 如果有稳定的类名，使用类名
        if (current.className && typeof current.className === "string") {
          const classes = current.className.trim().split(/\s+/);
          const stableClasses = classes.filter(
            (cls) =>
              !cls.match(
                /^(active|selected|hover|focus|disabled|loading|__element-picker)$/i
              )
          );
          if (stableClasses.length > 0) {
            selector += `.${stableClasses[0]}`;
          }
        }

        // 添加位置信息以确保唯一性
        const parent = current.parentElement;
        if (parent) {
          const siblings = Array.from(parent.children).filter(
            (child) => child.tagName === current.tagName
          );
          if (siblings.length > 1) {
            const index = siblings.indexOf(current) + 1;
            selector += `:nth-of-type(${index})`;
          }
        }

        path.unshift(selector);
        current = current.parentElement!;
      }

      return path.length > 0 ? path.join(" > ") : "";
    }

    // 手动启动引导
    function startPageTour(customStyles?: string) {
      const config = customStyles ? { customStyles } : undefined;
      const driver = getDriverInstance(config);
      driver.drive();
    }

    // 启动自定义引导
    function startCustomTour(customSteps: DriveStep[], customStyles?: string) {
      if (
        !customSteps ||
        !Array.isArray(customSteps) ||
        customSteps.length === 0
      ) {
        console.warn("自定义引导步骤为空或格式不正确");
        // 如果没有自定义步骤，回退到默认引导
        const config = customStyles ? { customStyles } : undefined;
        const driver = getDriverInstance(config);
        driver.drive();
        return;
      }

      console.log("开始验证自定义引导步骤:", customSteps);

      // 验证步骤中的元素是否存在
      const validSteps = customSteps.filter((step, index) => {
        if (!step.element) {
          console.warn(`步骤 ${index + 1} 缺少 element 属性:`, step);
          return false;
        }

        // 处理 DriveStep 的 element 字段可能是多种类型的情况
        let elementSelector: string;
        if (typeof step.element === "string") {
          elementSelector = step.element;
        } else if (typeof step.element === "function") {
          // 如果是函数，先执行获取元素，然后生成选择器
          try {
            const el = step.element();
            elementSelector = generateSelector(el);
          } catch (e) {
            console.warn(`步骤 ${index + 1}: 执行元素函数时出错:`, e);
            return false;
          }
        } else {
          // 如果是 Element，生成选择器
          elementSelector = generateSelector(step.element);
        }

        console.log(`验证步骤 ${index + 1} 的选择器: ${elementSelector}`);

        try {
          const element = document.querySelector(elementSelector);
          if (!element) {
            console.warn(`步骤 ${index + 1}: 未找到元素 "${elementSelector}"`);

            // 尝试提供相似的元素建议
            const tagName = elementSelector
              .replace(/[#.\[\]:]/g, "")
              .split(/[\s>+~]/)[0];
            if (tagName) {
              const similarElements = document.querySelectorAll(tagName);
              if (similarElements.length > 0) {
                console.log(
                  `找到 ${similarElements.length} 个相似的 ${tagName} 元素，建议检查选择器`
                );
              }
            }

            return false;
          }

          // 检查元素是否可见
          if (!isElementVisible(element)) {
            console.warn(
              `步骤 ${index + 1}: 元素 "${elementSelector}" 存在但不可见`
            );
          }

          console.log(`步骤 ${index + 1}: 元素验证成功 "${elementSelector}"`);
          return true;
        } catch (error) {
          console.error(
            `步骤 ${index + 1}: 选择器 "${elementSelector}" 语法错误:`,
            error
          );
          return false;
        }
      });

      if (validSteps.length === 0) {
        console.warn("没有找到有效的引导步骤元素");

        // 收集所有失败的选择器
        const failedSelectors = customSteps
          .map((step) => {
            if (typeof step.element === "string") {
              return step.element;
            } else if (typeof step.element === "function") {
              return "[Function]";
            } else if (step.element) {
              return generateSelector(step.element);
            }
            return null;
          })
          .filter(Boolean);

        // 显示详细的错误信息
        const fallbackConfig = {
          showProgress: true,
          customStyles,
          steps: [
            {
              element: "body",
              popover: {
                title: "未找到配置的元素",
                description: `页面中没有找到您配置的引导元素。\n\n失败的选择器:\n${failedSelectors
                  .map((s) => `• ${s}`)
                  .join(
                    "\n"
                  )}\n\n请检查元素选择器是否正确，或重新使用"选择元素"功能。`,
                side: "left",
                align: "start",
              },
            },
          ],
        };
        const fallbackDriver = getDriverInstance(fallbackConfig);
        fallbackDriver.drive();
        return;
      }

      console.log(`找到 ${validSteps.length} 个有效步骤，开始引导`);

      // 创建自定义引导实例
      const customConfig = {
        showProgress: true,
        customStyles,
        steps: validSteps,
      };
      const customDriver = getDriverInstance(customConfig);
      customDriver.drive();
    }

    // 检查元素是否可见
    function isElementVisible(element: Element) {
      const rect = element.getBoundingClientRect();
      return (
        rect.width > 0 &&
        rect.height > 0 &&
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= window.innerHeight &&
        rect.right <= window.innerWidth
      );
    }
  },
});
